gbDebug = True;
try:
  import xbmcgui;
except:
  # For command line testing outside of XBMC
  from FakeXBMCGUI import FakeXBMCGUI;
  xbmcgui = FakeXBMCGUI();

def ripDisc(oSettings, oDisc):
  import os;
  from runMakeMKVCon import runMakeMKVCon;
  oDialog = xbmcgui.Dialog();
  doTitle_by_iId = oDisc.getBranchesById();
  if oDisc.iSeason is not None:
    sOutputPath = os.path.join(oSettings.get("destination-path"), oDisc.sName, "Season %d" % oDisc.iSeason);
  else:
    sOutputPath = os.path.join(oSettings.get("destination-path"), "%s (%d)" % (oDisc.sName, oDisc.iYear));
  if not os.path.isdir(sOutputPath):
    os.makedirs(sOutputPath);
  iTitleCount = len(oDisc.getBranchesById());
  iTitleNumber = 0;
  iSuccessfulRipCount = 0;
  for iTitleId, oTitle in doTitle_by_iId.items():
    iTitleNumber += 1;
    while 1:
      sOutputFileName = oTitle.getInfo("output filename");
      sOutputFilePath = os.path.join(sOutputPath, sOutputFileName);
      sExtension = os.path.splitext(sOutputFileName)[1];
      if oDisc.bIsMovie:
        sDestinationFileName = "%s (%d)%s" % (oDisc.sName, oDisc.iYear, sExtension);
      elif oDisc.iSeason is None:
        sDestinationFileName = "%s - %02d%s" % (oDisc.sName, oDisc.iFirstEpisodeNumber + iTitleId, sExtension);
      else:
        sDestinationFileName = "%s - %dx%02d%s" % \
            (oDisc.sName, oDisc.iSeason, oDisc.iFirstEpisodeNumber + iTitleId, sExtension);
      sDestinationFilePath = os.path.join(sOutputPath, sDestinationFileName);
      if os.path.isfile(sOutputFilePath):
        if gbDebug:
          print "%s: Removing old output file %s" % (__file__, sOutputFilePath);
        try:
          os.remove(sOutputFilePath);
        except WindowsError:
          if not oDialog.yesno(oSettings.sName, "The output file already exists but cannot be removed.", \
              sOutputFilePath, "Would you like to try again?"):
            break;
      if os.path.isfile(sDestinationFilePath):
        if not oDialog.yesno(oSettings.sName, "The destination file already exists:", \
            sDestinationFilePath, "Would you like to overwrite it?"):
          break;
        if gbDebug:
          print "%s: Removing old destination file %s" % (__file__, sDestinationFilePath);
        os.remove(sDestinationFilePath);
      if iTitleCount == 1:
        sActionDescription = "Ripping to %s..." % sDestinationFileName;
      else:
        sActionDescription = "Ripping %d/%d to %s..." % (iTitleNumber, iTitleCount, sDestinationFileName);
      if gbDebug:
        print "%s: %s" % (__file__, sActionDescription);
        print "%s:   to %s" % (__file__, sOutputFilePath);
      iMinimalDuration = oSettings.get("minimal-duration-" + (oDisc.bIsMovie and "movie" or "tvshow"));
      bError, bCancelled, aasData = runMakeMKVCon(oSettings, sActionDescription,
          "--minlength=%d" % (iMinimalDuration * 60), "mkv", "dev:%s" % oDisc.sDeviceName, str(iTitleId), sOutputPath);
      if bError or bCancelled:
        if bCancelled and gbDebug:
          print "%s: Ripping canceled." % __file__;
        if os.path.isfile(sOutputFilePath):
          if gbDebug:
            print "%s: Removing old file %s" % (__file__, sOutputFilePath);
          try:
            os.remove(sOutputFilePath);
          except OSError, oOSError:
            if gbDebug:
              print "%s: Attempt to remove %s failed: %s" % (__file__, sOutputFilePath, oOSError.strerror);
        return False;
      if not os.path.isfile(sOutputFilePath):
        if gbDebug:
          print "%s: Ripping failed: there is no output file %s" % (__file__, sOutputFilePath);
        if oDialog.yesno(oSettings.sName, "Failed to rip title #%d." % iTitleId, "Would you like to try again?"):
          continue;
        break;
      if gbDebug:
        print "%s: Renaming output file %s" % (__file__, sOutputFilePath);
        print "%s:   to %s" % (__file__, sDestinationFilePath);
      os.rename(sOutputFilePath, sDestinationFilePath);
      iSuccessfulRipCount += 1;
      break;
    #for loop
  if iSuccessfulRipCount == 0:
    oDialog.ok(oSettings.sName, "Failed to rip disc.");
  elif iSuccessfulRipCount != iTitleCount:
    oDialog.ok(oSettings.sName, "Failed to rip %d/%d titles from disc." % (iTitleCount - iSuccessfulRipCount, iTitleCount));
  else:
    oDialog.ok(oSettings.sName, "Successfully ripped disc.");
  return True;